package com.itheima.service.imgl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.CustomerException;
import com.itheima.dto.SetmealDto;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {

        //添加套餐数据
        this.save(setmealDto);

        //添加套餐对应的菜品数据
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        setmealDishList.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishList);
    }

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //判断用户是否勾选
        if(ids.size()==0){
            throw new CustomerException("您未勾选任何数据");
        }
        //判断状态是否是禁用
        QueryWrapper<Setmeal> queryWrap1 = new QueryWrapper<>();
        queryWrap1.in("id",ids).eq("status",1);
        int count = this.count(queryWrap1);
        if(count>0){
            throw new CustomerException("套餐正在出售，不能删除");
        }
        //删除setmeal中的数据
        this.removeByIds(ids);

        //删除setmeal_dish中的数据
        QueryWrapper<SetmealDish> queryWrap2 = new QueryWrapper<>();
        queryWrap2.in("setmeal_id",ids);
        setmealDishService.remove(queryWrap2);

    }
}
